<?php

namespace Admin\Logic;

use Common\Model\MessageModel;

class MessageLogic extends MessageModel
{
	private $key = '72969e04baa8b6e43fae34e1969d56a6';
	
	protected function _initialize()
	{
		parent::_initialize();
	}
	
	public function getPage($search = array(),&$pageShow = null,$pageSize = 10)
	{
		$where = empty($search) ? array() : sprintf('LOCATE("%1$s",message_mobile)',$search);
	
		$count = $this->where($where)->count();
	
		$data = $this->where($where)->pagination($count,$pageShow,$pageSize)->order('message_id DESC')->getItems();
	
		foreach ($data as $key => &$item)
		{
			$item['state'] = get_format_state($item['message_state'], array('INIT'=>'初始化','SUCCESS'=>'成功','FAIL'=>'失败'));
			$item['template'] = get_format_state($item['message_template'], $this->getTemplate());
			$item['detail'] = get_format_url('detail', $item['message_id']);
		}
		 
		return $data;
	}
	
	public function getDetail($pk = 0)
	{
		$item = $this->getItem($pk);
		
		$item['state'] = get_format_state($item['message_state'], array('INIT'=>'初始化','SUCCESS'=>'成功','FAIL'=>'失败'));
		$item['template'] = get_format_state($item['message_template'], $this->getTemplate());
		
		return $item;
	}
	
	public function setSendData($data = array())
	{
		if( empty($data) )
		{
			return false;
		}
		
		if( empty($data['mobile']) === false )
		{
			// 简单验证手机号格式
			if( preg_match('/^1([0-9]{9})/',$data['mobile']) == false )
			{
				$this->error = '手机号不合法';
				
				return false;
			}
		}
		else
		{
			$this->error = '手机号不能为空';
				
			return false;
		}
		
		if( empty($data['template']) )
		{
			$this->error = '模板不能为空';
				
			return false;
		}
		
		switch ($data['template']) {
			case 'code':
				if( empty($data['content']) === false )
				{
					$this->error = '验证码由后台随机生成，无需填写';
					
					return false;
				}
				
			break;
			
			case 'text':
				if( empty($data['content']) )
				{
					$this->error = '请填写自定义短信内容';
						
					return false;
				}
			break;
			
			default:
				if( empty($data['content']) )
				{
					$this->error = '请填写短信内容';
						
					return false;
				}
			break;
		}
		
		$data['timestamp'] = time();
			
		$data['sign'] = getsign($data,'md5',$this->key);
		
		return $data;
	}
	
	public function sendData($data = array())
	{
		$curl = new \Org\Net\Http\Curl();
		
		$result = $curl->post(U('App/Message/send','','',true),$data);
		
		if( $curl->error )
		{
			$this->error = $curl->errorMessage;
			
			return false;
		}
		
		$resultArr = json_decode(json_encode($result,JSON_UNESCAPED_UNICODE),true);
		
		if( is_array($resultArr) === false )
		{
			$this->error = '返回参数格式有误';
			return false;
		}
		
		if( $resultArr['state'] == 1 && $resultArr['data']['message_state'] == 'SUCCESS' )
		{
			return true;
		}
		else
		{
			$this->error = $resultArr['msg'];
			
			return false;
		}
	}
	
	public function getTemplate()
	{
		return array(
				'code'=>'验证码模板',
				'text' => '自定义文本',
		);
	}
	
}
